<?php

namespace App\Models;

use App\Jobs\FleaUserWithdrawal;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

/**
 * Class FleaWallet
 * @package App\Models
 * 跳蚤市场钱包模型
 */
class FleaWallet extends Model
{
    protected $table = 'flea_wallet';

    protected $guarded = [];

    protected $casts = [
        'created_at' => 'datetime:Y-m-d H:i:s'
    ];

    protected function serializeDate(\DateTimeInterface $date)
    {
        return $date->format($this->dateFormat ?: 'Y-m-d H:i:s');
    }

    /**
     * 获取我的钱包信息
     */
    public static function getMyWalletData()
    {
        $user_id = auth('user')->id();
        if (!$user_id) {
            throw new \Exception('请先登录');
        }

        //可用余额
        $flea_money = User::query()->where('id', $user_id)->value('flea_money');
        //累计收入
        $amount_income = FleaRecord::query()->where(['user_id' => $user_id, 'type' => 1])->sum('money');
        //累计提现金额
        $takeout_money = FleaRecord::query()->where(['user_id' => $user_id, 'type' => 2])->sum('money');

        return ['flea_money' => $flea_money, 'amount_income' => $amount_income, 'takeout_money' => $takeout_money];
    }

    /**
     * @param $where
     * @param $time string 年月
     * @param $page
     * @param $limit
     * 用户累计收入 提现记录列表
     */
    public static function recordList($where, $time, $page, $limit)
    {
        $user_id = auth('user')->id();
        if (!$user_id) {
            throw new \Exception('请先登录');
        }

        $start = date('Y-m-01', strtotime($time));
        $end = date('Y-m-t', strtotime($time));

        $where[] = ['user_id', '=', $user_id];

        $offset = ($page == 1) ? 0 : ($page - 1) * $limit;
        $data = FleaRecord::query()->select('id', 'type', 'money', 'msg', 'order_id', 'created_at')->where($where)->whereBetween('created_at', [$start, $end])->offset($offset)->limit($limit)->get();

        $response['data'] = $data;
        $response['count'] = FleaRecord::query()->where($where)->whereBetween('created_at', [$start, $end])->count();
        $response['sum'] = FleaRecord::query()->where($where)->whereBetween('created_at', [$start, $end])->sum('money');
        $response['pages'] = ceil($response['count'] / $limit);

        return $response;
    }

    /**
     * @param $money int 用户申请提现
     */
    public static function takeout(int $money)
    {
        $user_id = auth('user')->id();
        if (!$user_id) {
            throw new \Exception('请先登录');
        }

        //开启事务
        DB::beginTransaction();
        try {
            //查询用户可用余额
            $flea_money = User::query()->where('id', $user_id)->value('flea_money');
            //判断是否合法
            if ($flea_money < $money) {
                throw new \Exception('超出可用余额');
            }
            //用户跳蚤市场钱包余额扣除提现金额
            User::query()->where('id', $user_id)->decrement('flea_money', $money);

            //查询后台是否自动提现
            $config = Config::query()->where('name', 'flea_withdrawal')->value('val');
            $config = json_decode($config, true);
            $insert = [
                'user_id' => $user_id,
                'money' => $money
            ];
            if (!empty($config['switch']) && $config['switch'] == true) {
                //声明变量
                $automatic = true;
                $insert['state'] = 2;
                $insert['examine_at'] = date('Y-m-d H:i:s');
            }

            //用户提现表写入数据
            $model = FleaWithdrawal::query()->create($insert);

            //用户金额记录表插入记录
            FleaRecord::query()->create([
                'user_id' => $user_id,
                'type' => 2,
                'msg' => '用户提现',
                'money' => $money,
                'order_id' => $model->id
            ]);

            //插入队列
            if (isset($automatic)) {
                //账户转账  插入到消息队列 1分钟后执行  测试环境设置0
                FleaUserWithdrawal::dispatch($model->id)->onQueue('FleaUserWithdrawal')->delay(now()->addMinutes(0));
            }
            //提交事务
            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            throw new \Exception($exception->getMessage());
        }
    }

    /**
     * @param $user_id int 用户ID
     * @param $where
     * @param $time string 年月
     * @param $page
     * @param $limit
     * 用户累计收入 提现记录列表
     */
    public static function adminRecordList($user_id, $where, $time, $page, $limit)
    {

        $start = date('Y-m-01', strtotime($time));
        $end = date('Y-m-t', strtotime($time));

        $where[] = ['user_id', '=', $user_id];

        $offset = ($page == 1) ? 0 : ($page - 1) * $limit;
        $data = FleaRecord::query()->select('id', 'user_id', 'type', 'money', 'msg', 'order_id', 'created_at')->where($where)->whereBetween('created_at', [$start, $end])->offset($offset)->limit($limit)->get();

        $response['data'] = $data;
        $response['count'] = FleaRecord::query()->where($where)->whereBetween('created_at', [$start, $end])->count();
        $response['sum'] = FleaRecord::query()->where($where)->whereBetween('created_at', [$start, $end])->sum('money');
        $response['pages'] = ceil($response['count'] / $limit);

        return $response;
    }
}
